import os
import json
import pendulum
import stat
import time
import datetime

from loguru import logger




class UtilsBox:
    # logger = getLogger(__name__)  # scrapy模块的日志,写入settings文件中定义的LOG_FILE文件中
    @staticmethod
    def mkdir(dirpath):
        if not os.path.exists(dirpath):
            os.makedirs(dirpath)

    @staticmethod
    def get_timestamp_of_today():
        today = datetime.date.today()
        timeArray = time.strptime(str(today), "%Y-%m-%d")
        timestamp = int(time.mktime(timeArray))
        return timestamp

    @staticmethod
    def now_time_str(date_format="%Y%m%d%H%M%S"):
        now = int(time.time())
        time_local = time.localtime(now)
        str = time.strftime(date_format, time_local)
        return str  # 20190806103523


    # 时间戳转日期
    @staticmethod
    def timestamp2datetime(timestamp, format='ys'):
        """
        将int 类型的timeStamp,eg:1571234123
        转为str类型的时间字符串,eg:2019-10-16 21:55:23
        """
        time_local = time.localtime(timestamp)
        datetime = ''
        if format == 'ys':
            datetime = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        elif format == 'yd':
            datetime = time.strftime("%Y-%m-%d", time_local)
        elif format == 'hs':
            datetime = time.strftime("%H:%M:%S", time_local)
        return datetime

    @staticmethod
    def dts2ts(dts):
        '''
        :param dts: '2019-06-07 16:30:10'   str
        :return: 1559896210                 int
        '''
        return int(time.mktime(time.strptime(dts, '%Y-%m-%d %H:%M:%S')))

    @staticmethod
    def ts2dts(ts):
        """
        将int 类型的timeStamp,eg:1571234123
        转为str类型的时间字符串,eg:2019-10-16 21:55:23
        """
        import time
        timeArray = time.localtime(ts)
        datestr = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
        return datestr


    # 日期转时间戳
    @staticmethod
    def datetime_str2timestamp(datestr):
        """
        datestring translate to timestamp
        :param datestr:
        :return:
        """
        if len(datestr) <= 10:
            datestr_format = "%Y-%m-%d"
        else:
            datestr_format = "%Y-%m-%d %H:%M:%S"
        timeArray = time.strptime(datestr, datestr_format)
        timeStamp = int(time.mktime(timeArray))
        return timeStamp



    @classmethod
    def purge_string(self, instring):
        """
        去掉数据中的空格换行等字符
        :param instring:
        :return:
        """
        move = dict.fromkeys((ord(c) for c in u"\xa0\n\t|│:：<>？?\\/*’‘“”\"\x01\x02"))
        outstring = instring.translate_data(move)
        return outstring

    @staticmethod
    def save_text(file=None, text=None, mode='w'):
        file_path = os.path.abspath(file)
        file_dir_path = os.path.dirname(file_path)
        if not os.path.exists(file_dir_path):
            os.makedirs(file_dir_path)
        with open(file, mode=mode, encoding='utf8') as f:
            f.write(text)

    @staticmethod
    def trans_json_text_to_json(text_file_path):
        with open(text_file_path, 'r', encoding='utf8') as f:
            json_str = f.read()
        json_obj = json.loads(json_str)
        return json_obj

    @staticmethod
    def extract_from_dict(keys=[], data={}):
        '''返回data字典中包含keys字段的部分'''
        new_dict = {}
        for k in keys:
            new_dict[k] = data.get(k)
        return new_dict

    @staticmethod
    def datediff(beginDate, endDate):
        '''参数类型:str, 返回值类型: int'''
        format = "%Y-%m-%d"
        bd = datetime.datetime.strptime(beginDate, format)
        ed = datetime.datetime.strptime(endDate, format)
        oneday = datetime.timedelta(days=1)
        count = 0
        while bd != ed:
            ed = ed - oneday
            count += 1
        return count

    @staticmethod
    def get_date_str_from_today(
            years=0,
            months=0,
            weeks=0,
            days=0,
            hours=0,
            minutes=0,
            seconds=0,
            microseconds=0,
    ):
        date_str = str(pendulum.today().add(
            years=years,
            months=months,
            weeks=weeks,
            days=days,
            hours=hours,
            minutes=minutes,
            seconds=seconds,
            microseconds=microseconds,
        )).split('T')[0]
        '''2008-01-01格式'''
        return date_str

    @staticmethod
    def get_the_date_from_a_date(date_str, days_delta=0):
        '''比如获取2019-07-23这一天之后days_delta天的日期'''
        year, month, day = [int(i) for i in date_str.split('-')]
        date = datetime.datetime(year, month, day)
        result_date = date + datetime.timedelta(days=days_delta)
        date_str = result_date.strftime('%Y-%m-%d')
        return date_str

    @staticmethod
    def today():
        '''返回值类型<class 'datetime.date'>'''
        today = datetime.date.today()
        print(today, type(today))
        return today

    @staticmethod
    def dict_dumps(data):
        '''将字典转为字典样式的字符串,主要转换datetime类型的value'''
        new_data = {}
        for k, v in data.items():
            new_data[k] = str(v)
        return json.dumps(new_data, ensure_ascii=False)

    @staticmethod
    def dict_dumps_date_keys(data):
        new_data = {}
        for k, v in data.items():
            if 'datetime' in type(v):
                new_data[k] = str(v)
            else:
                new_data[k] = v

        return new_data

    @staticmethod
    def trans_date(date_str='20080101'):
        y = date_str[:4]
        m = date_str[4:6]
        d = date_str[-2:]
        date = '-'.join([y, m, d])
        return date


t = UtilsBox().get_timestamp_of_today()
if __name__ == "__main__":
    u = UtilsBox()
    # t = u.get_timestamp_of_today()
    # print(t)
    # s = "\xa0\n\t|的女生多久啥地方呢│:：<>？?\\sdsd/*’‘“”\""
    # so = u.purge_string(s)
    # so = u.timestamp2datetime(1564019844)
    # so = u.timestamp2datetime(1564040912)
    # so = u.now_time_num_str()
    # so = u.timestamp2datetime(1552406400)
    so = str(u.today())
    print(so,type(so))
